package com.zhb86.kuaipai.ui.main;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.superyee.commonlib.constants.AppConfig;
import com.superyee.commonlib.constants.StaticConstant;
import com.superyee.commonlib.ui.BaseActivity;
import com.superyee.commonlib.ui.BaseFragment;
import com.superyee.commonlib.utils.AndroidUtil;
import com.superyee.commonlib.utils.StatusBarUtil;
import com.superyee.commonlib.widgets.BaseDialog;
import com.superyee.commonlib.widgets.BottomTabView;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhb86.kuaipai.R;
import com.zhb86.kuaipai.ui.city.FTabCity;
import com.zhb86.kuaipai.ui.home.FTabHome;
import com.zhb86.kuaipai.ui.mine.FTabMine;
import com.zhb86.kuaipai.ui.msg.FTabMsg;
import com.zhb86.live.ui.AVStreamingActivity;
import com.zhb86.live.ui.LivePlayer;
import com.zhb86.live.ui.StreamingBaseActivity;


import io.reactivex.functions.Consumer;

public class ATMain extends BaseActivity {


    private BottomTabView[] mTabViews = new BottomTabView[4];
    private BaseFragment[] mFragments = new BaseFragment[4];
    private View mBottomtabLayout;
    private int mCurrentPosition = 0;
    RxPermissions mRxPermissions;
    private BaseDialog mTipDialog;

    @Override
    protected int getLayoutId() {
        StatusBarUtil.transparencyStatusBar(this);
        return R.layout.activity_main;
    }


    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putInt(StaticConstant.Extra.INDEX, mCurrentPosition);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void initPerData(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(StaticConstant.Extra.INDEX, 0);
            BaseFragment homeTab = (BaseFragment) getSupportFragmentManager().findFragmentByTag(FTabHome.class.getSimpleName());
            if (homeTab == null) {
                homeTab = new FTabHome();
            }
            BaseFragment cityTab = (BaseFragment) getSupportFragmentManager().findFragmentByTag(FTabCity.class.getSimpleName());
            if (cityTab == null) {
                cityTab = new FTabCity();
            }
            BaseFragment msgTab = (BaseFragment) getSupportFragmentManager().findFragmentByTag(FTabMsg.class.getSimpleName());
            if (msgTab == null) {
                msgTab = new FTabMsg();
            }
            BaseFragment mineTab = (BaseFragment) getSupportFragmentManager().findFragmentByTag(FTabMine.class.getSimpleName());
            if (mineTab == null) {
                mineTab = new FTabMine();
            }
            mFragments[0] = homeTab;
            mFragments[1] = cityTab;
            mFragments[2] = msgTab;
            mFragments[3] = mineTab;
        } else {  // 正常时
            mFragments[0] = new FTabHome();
            mFragments[1] = new FTabCity();
            mFragments[2] = new FTabMsg();
            mFragments[3] = new FTabMine();
        }
    }


    @Override
    protected void initView() {
        mBottomtabLayout = findViewById(R.id.bottomtabLayout);
        mTabViews[0] = findViewById(R.id.tabHome);
        mTabViews[1] = findViewById(R.id.tabCity);
        mTabViews[2] = findViewById(R.id.tabMsg);
        mTabViews[3] = findViewById(R.id.tabMine);
        findViewById(R.id.btnPublish).setOnClickListener(view -> showPublishMenu());
        for (int i = 0; i < mTabViews.length; i++) {
            int pos = i;
            mTabViews[i].setOnClickListener(view -> {
                if (mCurrentPosition == pos) {
                    //刷新
                } else {
                    showHideFragment(mCurrentPosition, pos);
                    mTabViews[mCurrentPosition].setSelected(false);
                    mTabViews[pos].setSelected(true);
                    mCurrentPosition = pos;
                }
            });
        }
        showHideFragment(mCurrentPosition, mCurrentPosition);
        mTabViews[mCurrentPosition].setSelected(true);
    }

    private void showPublishMenu() {
        BaseDialog mDialog = new BaseDialog(this);
        mDialog.addItem("开直播", view -> {
            mDialog.dismiss();
            startLive();
        });
        mDialog.addItem("看直播", view -> {
            mDialog.dismiss();
            lookLive();
        });
        mDialog.show();
    }

    private void startLive() {
        if (mRxPermissions == null) {
            mRxPermissions = new RxPermissions(this);
        }
        String[] permissionGroup = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
        mRxPermissions.requestEachCombined(permissionGroup).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                if (permission.granted) {
                    Intent intent = new Intent(ATMain.this, AVStreamingActivity.class);
                    intent.putExtra(StreamingBaseActivity.INPUT_URL, AppConfig.LIVE_PUBLISH_URL);
                    startActivity(intent);
                } else if (!permission.shouldShowRequestPermissionRationale) {
                    //用户拒绝并选择不再提示
                    showPermissionTip();
                } else {
                    AndroidUtil.showToast(ATMain.this, "该功能需要使用[麦克风,相机]权限,请选择允许");
                }
            }
        });
    }

    private void showPermissionTip() {
        BaseDialog.closeDialog(mTipDialog);
        mTipDialog = new BaseDialog(this);
        mTipDialog.addChoose("取消", view -> BaseDialog.closeDialog(mTipDialog));
        mTipDialog.addChoose("去设置", view -> {
            BaseDialog.closeDialog(mTipDialog);
            AndroidUtil.goToAppDetail(ATMain.this, getPackageName());
        });
        mTipDialog.show();
        mTipDialog.setMsgText("该功能需要使用【麦克风,相机】权限");
    }

    private void lookLive() {
        Intent intent = new Intent(this, LivePlayer.class);
        startActivity(intent);
    }

    private void showHideFragment(int hide, int show) {
//        if (show == 0) {
//            mBottomtabLayout.setBackgroundResource(android.R.color.transparent);
//        } else {
//            mBottomtabLayout.setBackgroundResource(R.color.bottombar_bg_color);
//        }
        FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
        trx.hide(mFragments[hide]);
        Fragment showFragment = mFragments[show];
        if (!showFragment.isAdded() && null == getSupportFragmentManager().findFragmentByTag(showFragment.getClass().getSimpleName())) {
            trx.add(R.id.container, showFragment, showFragment.getClass().getSimpleName());
        }
        trx.show(showFragment).commitAllowingStateLoss();
    }

    private long firstBackPressedTime = 0;

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstBackPressedTime > 2000) {
            AndroidUtil.showToast(this, "再按一次退出");
            firstBackPressedTime = secondTime;
            return;
        }
        AndroidUtil.clearToast();
        super.onBackPressed();
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void addListener() {

    }

    @Override
    protected void removeListener() {
        BaseDialog.closeDialog(mTipDialog);
    }

    @Override
    public void onReceiverNotify(int action, Object obj, int statusCode) {

    }

}
